/**
* @describe 社交游戏房间socket类
* @author 游金宇(KM)
* @date 2024-09-12 11:41:27
*/


import { RoomEvent, Room, RoomSchema, SeatSwapApplySchema, RoomKickSchema, IMMessageSchema, IMMessage, EventResponsePair } from '../Test'


import { log } from 'cc';


import { BUILD, DEBUG, EDITOR, RUNTIME_BASED } from 'cc/env';
import { cat, toJson } from '../Test';

/**房间事件对 */
const RoomEventResponsePairs: EventResponsePair<RoomEvent>[] = [
    /**房态变更 协议名称：Room.Info，返回参数：Room  */
    {
        event: RoomEvent.RoomInfo, responseType: RoomSchema, cb: (data) => {
            cat.store.room.roomInfo = data as Room
            log('----------------------房间事件对 roomInfo', cat.store.room.roomInfo)
        }
    },
    /**交换座位申请 协议名称： Room.SeatSwapApply，返回参数：SeatSwapApply*/
    { event: RoomEvent.RoomSeatSwapApply, responseType: SeatSwapApplySchema },
    /**房间踢出 协议名称： Room.Kick，返回参数：RoomKick*/
    { event: RoomEvent.RoomKick, responseType: RoomKickSchema },
    /**房内聊天消息 协议名称： Room.Kick，返回参数：IMMessage*/
    {
        event: RoomEvent.RoomMessage, responseType: IMMessageSchema, cb: (data) => {
            const nonce = toJson(IMMessageSchema, data as IMMessage)
            window.MINI_GAME_SDK.chat.send({ data: nonce });
        }
    },
]


export const CreateRoomWebSocket = () => {
    log('创建room ws')
    return cat.room_ws = cat.socialGameClient?.createWebSocket(
        'room',
        {
            url: cat.env.room_ws_url,
            debug: DEBUG,
            isAutoConnect: true,
        },
        {
            token: cat.store.login.room_token
        },
        {
            normalEvents:
                new Map(RoomEventResponsePairs.map(({ event, responseType, cb }) => [
                    event,
                    { event, responseType, cb }
                ])),
        }
    )
}





